import { ipcMain } from 'electron'
import type { IpcMainEvent, IpcMainInvokeEvent } from 'electron'
import wallpaper from 'wallpaper'
import { downloadFile } from '../utils'
import { resolve } from 'node:path'
import fs from 'node:fs'

// 注意安装的是 CommonJS 版本
// npm install node-fetch@2
ipcMain.on('setWallpaper', async (_event: IpcMainEvent, url: string, path: string) => {
  // 将图片保存到本地文件夹
  const localFile = resolve(path, url.split('/').pop()!)

  const file = await downloadFile(url, localFile)

  // npm install wallpaper@v5.0.1
  wallpaper.set(file, { screen: 'all', scale: 'auto' })
})

ipcMain.handle('checkDirectory', async (_event: IpcMainInvokeEvent, path: string) => {
  return fs.existsSync(path)
})
